import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入一级路由
import Layout from '@/views/layout.vue'
import Login from '@/views/login.vue'
import Detail from '@/views/detail.vue'
import Register from '@/views/register.vue'

// 导入二级路由
import Collect from '@/views/collect.vue'
import Article from '@/views/article.vue'
import Like from '@/views/like.vue'
import User from '@/views/user.vue'
import NotFound from '@/views/NotFound.vue'
import { getToken } from '@/utils/Mytoken'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: 'article',
    children: [
      { path: '/collect', component: Collect },
      { path: '/article', component: Article },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// 配置导航守卫(路由拦截)
router.beforeEach((to, from, next) => {
  if (getToken()) {
    next()
  } else {
    if (to.path === '/login' || to.path === '/register') {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
